#include "mythread.h"

pthread_mutex_t pthreadMutex;//线程互斥锁
pthread_cond_t cond;//线程同步信号
pthread_mutexattr_t attr;

mythread::mythread(int sleeptime, QObject *parent) :
    QThread(parent)
{
    eCat=NULL;
    isRun = true;
    timeInval = sleeptime;

    //线程锁初始化
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setprotocol(&attr,PTHREAD_PRIO_INHERIT);
    pthread_mutex_init(&pthreadMutex,&attr);
    // setPriority(Priority priority);
}


void mythread::run()
{

   if(eCat==NULL){
       eCat=new CoeEcatDevice( );
   }
   eCat->cycleClock=timeInval;
  eCat->init();


#if 1

  struct sched_param param;
  param.__sched_priority = 99;
  sched_setscheduler(0,SCHED_FIFO,&param);
  //this->setStackSize(81920);
  int policy, priority;
  pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);

    while(isRun) {
        eCat->ecatUpdate( );
    }
#else

  /// clockid--值：CLOCK_REALTIME  , CLOCK_MONOTONIC  ， CLOCK_PROCESS_CPUTIME_ID  , CLOCK_THREAD_CPUTIME_ID
  /// evp--存放环境值的地址,结构成员说明了定时器到期的通知方式和处理方式等
  /// timerid--定时器标识符
 /* create a timer */
  struct sigevent evp;
  memset(&evp, 0, sizeof(struct sigevent));
  evp.sigev_notify = SIGEV_SIGNAL;//SIGEV_SIGNAL  ,  SIGEV_THREAD(通知的方式，派驻新线程 )
  evp.sigev_signo = SIGRTMIN;//SIGRTMIN实时信号(可靠信号)
  //  evp.sigev_value.sival_ptr = 0;  // 若是线程机制传递的参数
  //  evp.sigev_value.sival_int = 111;           // 信号机制传递的参数   //也是标识定时器的， 回调函数可以获得
  evp.sigev_notify_function =   timer_notify_fun;
  evp.sigev_notify_attributes = NULL; //  线程函数的属性  当 sigev_notify_attributes 非空，则制定该线程的属性
  timer_create(CLOCK_MONOTONIC, &evp, &timerid) ;

  ///  int timer_settime(timer_t timerid, int flags, const struct itimerspec *new_value,struct itimerspec *old_value);
  /// timerid--定时器标识
  /// flags--0表示相对时间，1表示绝对时间
  /// new_value--定时器的新初始值和间隔，如下面的it
  /// old_value--取值通常为0，即第四个参数常为NULL,若不为NULL，则返回定时器的前一个值
  ///第一次间隔it.it_value这么长,以后每次都是it.it_interval这么长,就是说it.it_value变0的时候会装载it.it_interval的值
  /* start a timer */
  struct timespec spec;
  struct itimerspec value;
  clock_gettime(CLOCK_REALTIME, &spec); /* CLOCK_REALTIME */
  value.it_value.tv_sec = spec.tv_sec ;
  value.it_value.tv_nsec = spec.tv_nsec + 1000000;//1ms
  value.it_interval.tv_sec = 0;    /* per second */
  value.it_interval.tv_nsec = 1000000;
  timer_settime(timerid, TIMER_ABSTIME, &value, NULL); /* TIMER_ABSTIME =0*/


  struct sched_param param;
  param.__sched_priority = 99;
  sched_setscheduler(0,SCHED_FIFO,&param);
  //this->setStackSize(81920);
  int policy, priority;
  // pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);
  pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);


#endif

    qDebug()<<"ethercat thread exit !";
    exec();
}
